package com.sduept.nwld.dataserver.manager.message;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.fault.common.ParamDesc;
import com.sduept.core.ParamManager;
import com.sduept.core.entity.SystemParameter;
import com.sduept.nwld.dataserver.exceptions.MessageException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * APP消息推送
 * @author Author
 * @version V1.0
 * @Date 2018年8月21日 上午9:21:45
 */
@Service
@Slf4j
public class APPMessagePushManager {

	@Autowired
	private ParamManager pc;


	public static final String SPLITSIGN = ",";
	
	
	/**
	 * 多人推送相同的APP消息
	 * @param persons
	 * @param title
	 * @param content
	 * @param sourceId
	 * @return
	 * @throws Exception
	 */
	public boolean messagePush(List<String> accounts,String title,String content,String sourceId) throws MessageException{
		if(accounts.size() == 0) {
			log.warn("发送短信的账号为空，内容："+content);
			return true;
		}
		StringBuilder temAccount = new StringBuilder();
		for (String account : accounts) {
			temAccount.append(account + SPLITSIGN);
		}
		String account = temAccount.toString();
		account = account.substring(0, account.lastIndexOf(SPLITSIGN));
		return messagePush(account,title,content,sourceId);
	}
	
	
	/**
	 * 单人推送APP消息
	 * @param account
	 * @param title
	 * @param content
	 * @param sourceId
	 * @return
	 */
	public boolean messagePush(String account,String title,String content,String sourceId) throws MessageException{
		if (StringUtils.isEmpty(account)) {
			throw new MessageException("账户不能为空");
		}
		if (StringUtils.isEmpty(title)) {
			throw new MessageException("标题不能为空");
		}
		if (StringUtils.isEmpty(content)) {
			throw new MessageException("内容不能为空");
		}
		boolean result = false;
		JSONArray jsa = new JSONArray();
		JSONObject jso = new JSONObject();
		jso.put("title", title);
		jso.put("summary", content);
		jso.put("scheme", sourceId);
		jsa.add(jso);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("loginId", account));
		nvps.add(new BasicNameValuePair("events", jsa.toString()));
		try {
			result = push(nvps);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	/**
	 * APP消息推送 （调用平台接口）
	 * 返回值：true or false
	 * @param nvps
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	private boolean push(List<NameValuePair> nvps) throws ParseException, IOException {
		if (nvps.size() == 0) {
			return false;
		}
		SystemParameter parameter = pc.get(ParamDesc.NWLD_MOBILE_URL);
		if (null == parameter || StringUtils.isEmpty(parameter.getValue())) {
			return false;
		}
		// 手机端服务器地址
		String nwldMobileUrl = parameter.getValue();
		HttpPost httpPost = new HttpPost(nwldMobileUrl);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).
				setConnectionRequestTimeout(5 * 1000).setSocketTimeout(10 * 1000).setRedirectsEnabled(true).build();
		httpPost.setConfig(requestConfig);
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
		try (CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build(); 
				CloseableHttpResponse response = closeableHttpClient.execute(httpPost);) {
			if (response.getStatusLine().getStatusCode() == 200) {
				return true;
			} else {
				log.error("Error Response:" + response.getStatusLine().toString());
				return false;
			}
		}
	}

}
